package com.chenfan.process.biz.impl;

import com.chenfan.ccp.common.exception.ApiException;
import com.chenfan.process.biz.ProcessDetailBizService;
import com.chenfan.process.common.exception.ProcessResultCode;
import com.chenfan.process.entity.po.ApprovalTemplatePo;
import com.chenfan.process.entity.po.ProcessInstanceApprovePo;
import com.chenfan.process.entity.vo.ApprovalPersonVo;
import com.chenfan.process.service.ApprovalTemplateService;
import com.chenfan.process.service.ProcessDetailService;
import com.chenfan.process.service.ProcessInstanceApproveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author K
 * @date 2021/3/5
 */
@Service
public class ProcessDetailBizServiceImpl implements ProcessDetailBizService {

    @Autowired
    private ProcessDetailService processDetailService;
    @Autowired
    private ProcessInstanceApproveService processInstanceApproveService;
    @Autowired
    private ApprovalTemplateService approvalTemplateService;

    @Override
    public Collection<ApprovalPersonVo> getApprovals(String approvalTemplateCode) {
        ApprovalTemplatePo templatePo = approvalTemplateService.getByCode(approvalTemplateCode);
        if (Objects.isNull(templatePo)) {
            throw new ApiException(ProcessResultCode.TEMPLATE_NOT_EXISTS);
        }
        List<ProcessInstanceApprovePo> processInstanceApproves =
            processInstanceApproveService.listApprovingInstance(templatePo.getId());
        List<ApprovalPersonVo> collect = processInstanceApproves.stream()
            .map(e -> ApprovalPersonVo.builder().userId(e.getUserId()).userName(e.getUserName()).build())
            .collect(Collectors.toList());
        return new HashSet<>(collect);

    }

    @Override
    public Collection<ApprovalPersonVo> listApprovals(Collection<Long> approvalTemplateIdList) {
        List<ApprovalTemplatePo> templateList = approvalTemplateService.listByCode(approvalTemplateIdList);
        if (CollectionUtils.isEmpty(templateList)) {
            return new HashSet<>();
        }
        List<Long> templateIdList = templateList.stream().map(ApprovalTemplatePo::getId).collect(Collectors.toList());
        List<ProcessInstanceApprovePo> processInstanceApproves = processInstanceApproveService.listApprovingInstance(templateIdList);
        List<ApprovalPersonVo> collect = processInstanceApproves.stream()
            .map(e -> ApprovalPersonVo.builder().userId(e.getUserId()).userName(e.getUserName()).build())
            .collect(Collectors.toList());

        return new HashSet<>(collect);
    }
}
